package com.example.newdemo.net;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class InterceptorsDemo {


    Interceptor tokenInterceptor = new Interceptor() {  //全局拦截器，
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();//获取原始请求
            Request.Builder requestBuilder = originalRequest.newBuilder() //建立新的请求
                    .addHeader("Accept", "application/json")
                    .addHeader("Content-Type", "application/json; charset=utf-8")
                    .method(originalRequest.method(), originalRequest.body());
            return chain.proceed(requestBuilder.build()); //重新请求
        }
    };


    /**
     * 全局动态添加Token
     */
    Interceptor tokenInterceptors = new Interceptor() {  //全局拦截器，往请求头部添加 token 字段，实现了全局添加 token
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();//获取原始请求
            Request.Builder requestBuilder = originalRequest.newBuilder() //建立新的请求
                    .addHeader("Accept", "application/json")
                    .addHeader("Content-Type", "application/json; charset=utf-8")
//                    .removeHeader("User-Agent")
//                    .addHeader("User-Agent",BaseUtils.getUserAgent())
                    .method(originalRequest.method(),originalRequest.body());
//                Log.e("----------------",originalRequest.body().toString());
            Request tokenRequest = null; //带有token的请求

//            if (StringUtils.isEmpty(App.mmkv.decodeString(BaseConfig.TOKEN,null))){
//                return chain.proceed(requestBuilder.build());
//            }
//
//            tokenRequest = requestBuilder
//                    .header("Authorization","Bearer "+App.mmkv.decodeString(BaseConfig.TOKEN,null))
//                    .build();


            return chain.proceed(tokenRequest);
        }
    };


    /**
     * 自动判断token是否过期,过期无感刷新
     * 在进行网络交互的时候,服务端签发的Token是有时效性的而且一般比较短,
     * 过了有效期就需要重新请求,而这个过程我们不能让用户察觉到,所以需要实现用户无感知的情况下刷新请求新的Token.
     */
    Interceptor tokenRespInterceptor = new Interceptor() { //拦截返回体  判断token是否过期.过期重写拉取新的token
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Response response = chain.proceed(request);
//                KLog.d( response.body().string());

//            if (isTokenExpired(response)){
////                KLog.d( "自动刷新Token,然后重新请求数据");
//                //同步请求方式，获取最新的Token
//                String newToken = getNewToken();
//                if (newToken != null){
//                    //使用新的Token，创建新的请求
//                    Request newRequest = chain.request()
//                            .newBuilder()
//                            .header("Authorization", "Bearer " + newToken)
//                            .build();
//                    //重新请求
//                    return chain.proceed(newRequest);
//                }
//
//            }


//            return response.newBuilder().body(ResponseBody.create(MediaType.parse("UTF-8"),body)).build();
            return response;
        }
    };



    /**
     * 根据Response，判断Token是否失效
     *
     * @param response
     * @return
     */
    private boolean isTokenExpired(Response response) {
        String message = null;
        int code = -1 ;
        try {
            String body = response.body().string();
            JSONObject object = new JSONObject(body);
            message = object.getString("Message");
            code = object.getInt("Code");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if ("Token is expired".equals(message)&& code == 1) {
            return true;
        }
        return false;
    }

}
